package moni.anyou.com.view.tool;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.UUID;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.model.ObjectMetadata;
import android.app.Application;
import android.app.usage.NetworkStats.Bucket;
import android.util.Log;
import android.content.Context;

import moni.anyou.com.view.config.SysConfig;

public class UploadUtil {
    private static final String TAG = "uploadFile";
    private static final int TIME_OUT = 10*1000;   //超时时间
    private static final String CHARSET = "utf-8"; //设置编码
    //OSS的Bucket
    public static final String OSS_BUCKET = "qianmo88";
    //Key
    private static final String endpoint = "oss-cn-shanghai.aliyuncs.com";
    private static final String accessKey = "LTAIusWPLTwLyuyO";
    private static final String screctKey = "lwEFRbAMGpBto3qe7yUmDrtHMPllAV";
    /**
     * android上传文件到服务器
     * @param file  需要上传的文件
     * @param RequestURL  请求的rul
     * @return  返回响应的内容
     */
    public static int uploadFile(File file,String RequestURL)
    {

        String result = null;
        int responseCode = -1;
        String  BOUNDARY =  UUID.randomUUID().toString();  //边界标识   随机生成
        String PREFIX = "--" , LINE_END = "\r\n"; 
        String CONTENT_TYPE = "multipart/form-data";   //内容类型
        
        try {
        	
            URL url = new URL(RequestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(TIME_OUT);
            conn.setConnectTimeout(TIME_OUT);
            conn.setDoInput(true);  //允许输入流
            conn.setDoOutput(true); //允许输出流
            conn.setUseCaches(false);  //不允许使用缓存
            conn.setRequestMethod("POST");  //请求方式
            conn.setRequestProperty("Charset", CHARSET);  //设置编码
            conn.setRequestProperty("connection", "keep-alive");   
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); 
        	
            if(file!=null)
            {
                System.out.println(file.getName());
                /**
                 * 当文件不为空，把文件包装并且上传
                 */
                DataOutputStream dos = new DataOutputStream( conn.getOutputStream());
                StringBuffer sb = new StringBuffer();
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                /**
                 * 这里重点注意：
                 * name里面的值为服务器端需要key   只有这个key 才可以得到对应的文件
                 * filename是文件的名字，包含后缀名的   比如:abc.png  
                 */
                System.out.println(file.getName());
                sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""+file.getName()+"\""+LINE_END); 
                sb.append("Content-Type: application/octet-stream; charset="+CHARSET+LINE_END);
                sb.append(LINE_END);
                dos.write(sb.toString().getBytes());
                InputStream is = new FileInputStream(file);
                byte[] bytes = new byte[1024];
                int len = 0;
                while((len=is.read(bytes))!=-1)
                {
                    dos.write(bytes, 0, len);
                }
                is.close();
                dos.write(LINE_END.getBytes());
                byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
                dos.write(end_data);
                dos.flush();
                /**
                 * 获取响应码  200=成功
                 * 当响应成功，获取响应的流  
                 */
                 responseCode = conn.getResponseCode();
                Log.e(TAG, "response code:"+responseCode);
//                if(res==200)
//                {
                    //Log.e(TAG, "request success");
                    InputStream input =  conn.getInputStream();
                    StringBuffer sb1= new StringBuffer();
                    int ss ;
                    while((ss=input.read())!=-1)
                    {
                        sb1.append((char)ss);
                    }
                    result = sb1.toString();
                   // Log.e(TAG, "result : "+ result);
//                }
//                else{
//                    Log.e(TAG, "request error");
//                }
            }
        } catch (MalformedURLException e) {
        	
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseCode;
    }

    private static void initOSSConfig(Context context){
        if (SysConfig.oss  == null) {
          //  String endpoint = "http://oss-cn-shanghai.aliyuncs.com";
            OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(accessKey, screctKey);
            ClientConfiguration conf = new ClientConfiguration();
            conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
            conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
            conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
            conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
            SysConfig.oss = new OSSClient(context, endpoint, credentialProvider, conf);
        }
    }

    public static  void ossUpload(Context context,File file,String dir,String strPath) {
        initOSSConfig(context);
        String fileName = file.getName();
        // 指定数据类型，没有指定会自动根据后缀名判断
       // ObjectMetadata objectMeta = new ObjectMetadata();
        //objectMeta.setContentLength(formDataContentDisposition.getSize());

       // objectMeta.setContentType("image/jpeg");
        // 构造上传请求
        // 这里的objectKey其实就是服务器上的路径，即目录+文件名
        //因为目录命名逻辑涉及公司信息，被我删去，造成不知道这个objectKey不知为何物，如下是我们公司的大致命名逻辑
        //String objectKey = keyPath + "/" + carArr[times] + ".jpg";
       System.out.println("xxxxx----------------cccccccccccc-------------------------"+fileName);
        PutObjectRequest put = new PutObjectRequest(OSS_BUCKET, dir + "/" + fileName, strPath);
        //put.setMetadata(objectMeta);
        try {
            PutObjectResult putObjectResult = SysConfig.oss.putObject(put);
        } catch (Exception e) {
             System.out.println("xxxxx----------------cccccccccccc-------------------------"+e.toString());
        }
    }

        /**
         * 通过文件名判断并获取OSS服务文件上传时文件的contentType
         * @param fileName 文件名
         * @return 文件的contentType
         */
    public static final String getContentType(String fileName){
        String fileExtension = fileName.substring(fileName.lastIndexOf("."));
        if("bmp".equalsIgnoreCase(fileExtension)) return "image/bmp";
        if("gif".equalsIgnoreCase(fileExtension)) return "image/gif";
        if("jpeg".equalsIgnoreCase(fileExtension) || "jpg".equalsIgnoreCase(fileExtension)  || "png".equalsIgnoreCase(fileExtension) ) return "image/jpeg";
        if("html".equalsIgnoreCase(fileExtension)) return "text/html";
        if("txt".equalsIgnoreCase(fileExtension)) return "text/plain";
        if("vsd".equalsIgnoreCase(fileExtension)) return "application/vnd.visio";
        if("ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) return "application/vnd.ms-powerpoint";
        if("doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) return "application/msword";
        if("xml".equalsIgnoreCase(fileExtension)) return "text/xml";
        return "text/html";
    }

}